<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\goods\LihuaGoods;
use app\common\model\goods\LihuaStock;

/**
 * 商品
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 某门店某商品库存
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_id", type="int", required=true, description="商品ID")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566983511","data":{"stock":200}})
     */
    public function stock($store_id = 0, $goods_id = 0)
    {
       if ($store_id && $goods_id) {
           $num = LihuaStock::where(['goods_id' => $goods_id, 'store_id' => $store_id])->value('num');
           if (!is_null($num)) {
               $enable = LihuaGoods::where('id', $goods_id)->value('enable_stock');
               if ($enable == 0) $num = null;
           }
           $this->success('OK', ['stock' => $num]);
       }
       $this->error('参数错误');
    }

    /**
     * 某门店所有商品库存
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571299403","data":{"stocks":{"1180":5000,"2228":200}}})
     */
    public function stocks($store_id = 0)
    {
        if ($store_id) {
            $nums = LihuaStock::where('store_id', $store_id)->whereNotNull('num')->column('goods_id,num');
            if ($nums) {
                $goods_ids = array_keys($nums);
                $ids = LihuaGoods::whereIn('id', $goods_ids)->where('enable_stock', 1)->column('id');
                if ($ids) {
                    foreach ($nums as $k => $v) {
                        if (!in_array($k, $ids)) unset($nums[$k]);
                    }
                }
            }
            $this->success('OK', ['stocks' => $nums ? : null]);
        }
        $this->error('参数错误');
    }

}
